import { useState, useEffect } from "react";
import { Table, Select, DatePicker, Button, Row, Col, message, Space, Pagination } from "antd";
import type { TableProps } from "antd";
import dayjs from "dayjs";
import { t } from "@/locales/i18n";
import alarmService from "@/api/alarm/alarm";
import deviceService from "@/api/device/device";
import areaService from "@/api/device/area";
import type { AreaSelect, SectionSelect, AlarmHistoryItem } from "#/alarm";
import '../style/index.css'

const { RangePicker } = DatePicker;
const { Option } = Select;

function HistoryData() {
	const [listQuery, setListQuery] = useState({
		pageNo: 1,
		pageSize: 10,
		sectionName: undefined,
		alarmType: "污染",
		deviceId: undefined,
		areaId: undefined,
	});

	const [rangeDate, setRangeDate] = useState<[dayjs.Dayjs, dayjs.Dayjs]>();
	const [total, setTotal] = useState(0);
	const [list, setList] = useState<AlarmHistoryItem[]>([]);
	const [secName, setSecName] = useState("");
	const [secList, setSecList] = useState<SectionSelect[]>([]);
	const [copySecList, setCopySecList] = useState<SectionSelect[]>([]);
	const [loading, setLoading] = useState(false);
	const [areaList, setAreaList] = useState<AreaSelect[]>([]);
	const [areaName, setAreaName] = useState("");

	const alarmList = [
		{
			value: "污染",
			label: "污染",
		},
	];

	useEffect(() => {
		init();
	}, []);

	const init = async () => {
		await fetchAreaListData();
		await fetchSectionListData();
		setLoading(false);
	};

	const fetchAreaListData = async () => {
		try {
			setLoading(true);
			const response = await areaService.getAreaList();
			if (response?.data) {
				const areaData = response.data.map((item) => ({
					id: item.areaId,
					value: item.areaId,
					address: item.areaName,
					label: item.areaName,
				}));
				setAreaList(areaData);
			}
		} catch (err) {
			console.error("Error fetching area list:", err);
		} finally {
			setLoading(false);
		}
	};

	const fetchSectionListData = async () => {
		try {
			setLoading(true);
			const response = await deviceService.getDeviceList();
			if (response?.data) {
				const areaData = response.data;
				const sections = areaData.map((item, index) => ({
					index,
					id: item.deviceId,
					label: item.sectionName,
					value: item.sectionName,
					address: item.sectionName,
					areaId: item.areaId,
				}));
				setSecList(sections);
				setCopySecList(sections);
				setSecName(areaData[0].sectionName);
				setAreaName(areaData[0].areaId);
			}
		} catch (err) {
			console.error("Error fetching section list:", err);
		} finally {
			setLoading(false);
		}
	};

	const fetchAlarmHistoryList = async (page?: number, pageSize?: number) => {
		if (!checkQuery()) return;
		
		try {
			setLoading(true);
			const queryParams = {
				...listQuery,
				pageNo: page || listQuery.pageNo,
				pageSize: pageSize || listQuery.pageSize,
				areaId: areaName,
				sectionName: secName,
				beginDate: rangeDate?.[0].format("YYYY-MM-DD HH:mm:ss"),
				endDate: rangeDate?.[1].format("YYYY-MM-DD HH:mm:ss"),
			};

			const response = await alarmService.getAlarmHistoryList(queryParams);
			if (response?.data?.list) {
				setList(response.data.list);
				setTotal(response.data.count);
			}
		} catch (err) {
			console.error("Error fetching alarm history:", err);
		} finally {
			setLoading(false);
		}
	};

	const checkQuery = () => {
		if (!rangeDate) {
			message.warning("请选择日期");
			return false;
		}
		return true;
	};

	const handleAreaChange = (value: string) => {
		setAreaName(value);
		setSecName("");
		const filteredSections = secList.filter((item) => item.areaId === value);
		setCopySecList(filteredSections);
	};

	const columns: TableProps<AlarmHistoryItem>["columns"] = [
		{
			title: "时间",
			dataIndex: "alarmdate",
			fixed: "left",
		},
		{
			title: "断面名称",
			dataIndex: "sectionname",
		},
		{
			title: "类型",
			dataIndex: "alarmtype",
		},
		{
			title: "内容",
			dataIndex: "alarmreason",
		},
	];

	const handleExport = async () => {
		if (!checkQuery()) return;

		try {
			const queryParams = {
				...listQuery,
				sectionName: secName,
				areaId: areaName,
				alarmType: listQuery.alarmType,
				beginDate: rangeDate?.[0].format("YYYY-MM-DD HH:mm:ss"),
				endDate: rangeDate?.[1].format("YYYY-MM-DD HH:mm:ss"),
			};

			const response = await alarmService.exportSectionHistoryAlarm(queryParams);
			if (response) {
				// 创建 blob 对象
        const blob = new Blob([response], {
          type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        });

        // 创建下载链接并自动下载
        const link = document.createElement('a');
        const url = window.URL.createObjectURL(blob);
        link.href = url;
        link.download = `历史数据_${dayjs().format('YYYY-MM-DD_HH-mm-ss')}.xlsx`;
        document.body.appendChild(link);
        link.click();

        // 清理
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);
			} else {
				message.warning("没有查到数据");
			}
		} catch (err) {
			console.error("Error exporting data:", err);
		}
	};
	
  // 日期快捷选项
  const dateShortcuts = {
    items: [
      {
        label: '最近一周',
        value: [dayjs().subtract(7, 'day'), dayjs()]
      },
      {
        label: '最近一个月',
        value: [dayjs().subtract(30, 'day'), dayjs()]
      },
      {
        label: '最近三个月',
        value: [dayjs().subtract(90, 'day'), dayjs()]
      }
    ]
  };

	const handleReset = () => {
		setListQuery({
			pageNo: 1,
			pageSize: 10,
			sectionName: undefined,
			alarmType: "污染",
			deviceId: undefined,
			areaId: undefined,
		});
		setList([]);
		setTotal(0);
		setSecName("");
		setRangeDate(undefined);
		setAreaName("");
	};

	const handlePageChange = async (page: number, pageSize: number) => {
		setListQuery((prev) => ({ ...prev, pageNo: page, pageSize }));
		await fetchAlarmHistoryList(page, pageSize);
	};

	return (
		<div className="p-6 flex flex-col h-full">
			<div className="mb-4 flex-none">
				<Row gutter={[16, 16]} align="middle" wrap>
					<Col flex="320px">
						<div className="flex items-center">
							<label className="inline-block w-20 text-right mr-2">区域名称</label>
							<Select
								value={areaName}
								placeholder="请选择区域名称"
								onChange={handleAreaChange}
								className="w-full"
								allowClear
								showSearch
								options={areaList}
								filterOption={(input, option) =>
									(option?.label?.toString() ?? '').toLowerCase().includes(input.toLowerCase())
								}
							/>
						</div>
					</Col>
					<Col flex="320px">
						<div className="flex items-center">
							<label className="inline-block w-20 text-right mr-2">断面名称</label>
							<Select
								value={secName}
								placeholder="请输入断面名称"
								onChange={(value) => setSecName(value)}
								className="w-full"
								allowClear
								showSearch
								options={copySecList}
								filterOption={(input, option) =>
									(option?.label ?? '').toLowerCase().includes(input.toLowerCase())
								}
							/>
						</div>
					</Col>
					<Col flex="320px">
						<div className="flex items-center">
							<label className="inline-block w-20 text-right mr-2">告警类型</label>
							<Select
								value={listQuery.alarmType}
								placeholder="告警类型"
								onChange={(value) =>
									setListQuery((prev) => ({ ...prev, alarmType: value }))
								}
								className="w-full"
								allowClear
								showSearch
								options={alarmList}
								filterOption={(input, option) =>
									(option?.label ?? '').toLowerCase().includes(input.toLowerCase())
								}
							/>
						</div>
					</Col>
					<Col flex="420px">
						<div className="flex items-center">
							<label className="inline-block w-20 text-right mr-2">时间范围</label>
							<RangePicker
								showTime
								value={rangeDate}
								onChange={(dates) => setRangeDate(dates as [dayjs.Dayjs, dayjs.Dayjs])}
								className="w-full"
                presets={dateShortcuts.items}
							/>
						</div>
					</Col>
					<Col flex="auto" className="text-right">
						<Space>
							<Button type="primary" onClick={() => fetchAlarmHistoryList()}>
								搜索
							</Button>
							<Button onClick={handleReset}>
								重置
							</Button>
							<Button onClick={handleExport}>
								导出
							</Button>
						</Space>
					</Col>
				</Row>
			</div>

			<div className="flex-1 overflow-hidden relative">
				<Table
					columns={columns}
					dataSource={list}
					loading={loading}
					pagination={false}
					scroll={{ 
						x: true,
						y: 'calc(100vh - 310px)'
					}}
					className="custom-table"
				/>
				
				<div className="absolute bottom-0 right-0 w-full py-3 px-6">
					<div className="flex justify-end ">
						<Pagination
							total={total}
							size="small"
							current={listQuery.pageNo}
							pageSize={listQuery.pageSize}
							onChange={handlePageChange}
							showSizeChanger={true}
							showQuickJumper={true}
							showTotal={(total) => `共 ${total} 条`}
						/>
					</div>
				</div>
			</div>
		</div>
	);
}

export default HistoryData;

